<?php
if (!function_exists("myTitle")) {
    /**
     * 内容长度省略
     * @param $content
     * @param int $length
     */
    function myTitle(String $content, int $length = 10)
    {
        $content = html_entity_decode($content); // 对传入的文章内容
        if ($length > 0 && mb_strlen(trim($content), 'utf-8') > $length) {
            return mb_substr(trim($content), 0, $length, 'utf-8') . "...";
        } else {
            return trim($content);
        }
    }
}

if (!function_exists("en_substr")) {
    /**
     * 英文截取
     * @param $content
     * @param int $length
     */
    function en_substr(String $content, int $length = 10)
    {
        if (!empty($content) && $content != null) {
            $content = strip_tags($content); //去掉所有的html标签
            $content = mb_ereg_replace("\t", "", $content);
            $content = mb_ereg_replace("\r\n", "", $content);
            $content = mb_ereg_replace("\n", "", $content);
            $content = preg_replace('!\s+!', ' ', $content); // 多个空格变成一个
            $search = "&nbsp;"; // 多个&nbsp;变成一个&nbsp;
            $contentArr = explode($search, $content);
            $contentArr = array_unique($contentArr); // 去重
            $newContentArr = [];
            foreach ($contentArr as $key => $c) {
                if (!empty($c)) {
                    array_push($newContentArr, $c);
                }
            }
            $content = implode($search, $newContentArr);
            if ($length > 0 && mb_strlen(trim($content), 'utf-8') > $length) {
                return mb_substr(trim($content), 0, $length, 'utf-8') . "...";
            } else {
                return trim($content);
            }
        } else {
            return $content;
        }
    }
}
if (!function_exists('foxDate')) {
    /**
     * 时间转化日期格式
     * @param     string $format 日期格式
     * @param     intval $t 时间戳
     */
    function foxDate($format = 'Y-m-d', $t = '')
    {
        if (!empty($t)) {
            if (is_string($t)) {
                $t = strtotime($t);
            }
            $t = date($format, $t);
        }
        return $t;
    }
}
if (!function_exists('getFromPage')) {
    // 获取网站来源
    function getFromPage()
    {
        return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    }
}

if (!function_exists('getAccessIP')) {
    // 获取访问者id
    function getAccessIP()
    {
        static $realip;
        if (isset($_SERVER)) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")) {
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }
}

if (!function_exists('serverIP')) {
    // 服务器端IP
    function serverIP()
    {
        // 因为解析问题可能导致后台卡
        if (!empty($_SERVER['SERVER_ADDR']) && !preg_match('/127\.0\.\d{1,3}\.\d{1,3}/i', $_SERVER['SERVER_ADDR']) && !preg_match('/192\.168\.\d{1,3}\.\d{1,3}/i', $_SERVER['SERVER_ADDR'])) {
            $serviceIp = $_SERVER['SERVER_ADDR'];
        } else {
            $serviceIp = @gethostbyname($_SERVER["SERVER_NAME"]);
        }
        return $serviceIp;
    }
}
// 字节数Byte转换为KB、MB、GB、TB
function xn_file_size($size)
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $units[$i];
}
if(!function_exists('getNextPrevArticle')){
    // 获取上下篇在模板里{php调用} 
    function getNextPrevArticle($id,$pid)
    {    
        $map['status'] = 'normal';
        $map['category_id'] = $pid;
        $map['delete_time']=NULl;
        $list = \think\facade\Db::name('archives')->where($map)->order('weigh desc,publish_time desc,id desc')->select()->toArray(); 
        $prev = [];
        $next = [];
        foreach ($list as $key => $value) {
            if($value['id'] == $id){

                if(isset($list[$key-1])){
                    $prev = $list[$key-1];
                }else{
                    $prev=0;
                }

                if(isset($list[$key+1])){
                    $next = $list[$key+1];
                }else{
                    $next=0;
                }
            }
        }
        return ['prev'=>$prev,'next'=>$next];
    } 
}
// 判断是否为https
if (!function_exists('isHttps')) {
    function isHttps()
    {
        if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            return true;
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            return true;
        } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            return true;
        }
        return false;
    }
}
/**
 * 获取http类型
 */
if (!function_exists('httpType')) {
    /**
     * http 类型
     * @return string
     */
    function httpType()
    {
        return $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

    }
}

/**
 * md5判断
 * @param   string   $w   字符
 * @return  bool
 */
function is_md5($w){
    return preg_match("/^[a-f0-9]{32}$/", $w);
}

/**
 * 判断字符是否合乎规则
 * @param   string   $s   目标字符串
 * @param   string   $f   正则类型 ip,mobile,email 或者 允许有的位数范围,如:{1,3}
 * @param   array    $t   合法的字符集0:字母数字汉字下划线 1:数字 2:小写字母 3:大写字母 4:汉字 5:任何非空白字符
 * @param   string   $o   允许有字符
 * @return  bool
 */
function is_preg($s,$f='',$t=[0],$o=''){
    if($s=='' || is_array($s)) return false;
    $s = str_replace([chr(10),chr(13),"\t"],['','',''],$s);
    $p = [
        'ip'    => "/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",
        'mobile'=> "/^1[3|4|5|6|7|8|9]{1}[0-9]{9}$/",
        'email' => "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/",
        'class' => "/^[A-Z]{1}[a-zA-Z0-9]{1,15}$/",
        'idcard'=> "/^([1-6][1-9]|50)\d{4}(19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/"
    ];
    if(isset($p[$f])) return preg_match($p[$f],$s);
    $m = '/^[';
    $p = ['\w',"0-9",'a-z','A-Z','\x{4e00}-\x{9fa5}','\S'];
    foreach($t as $v){
        $m .= $p[$v] ?? '';
    }
    $m .= $o ? $o.']'.$f.'+$/u' : ']'.$f.'+$/u';
    return preg_match($m,$s);
}

/**
 * 返回字符串长度
 * @param   string  $s  目标源
 * @return  int
 */
function word_count($s){
    return function_exists('mb_strlen') ? mb_strlen($s, 'utf8') : strlen($s);
}

/**
 * 生成指定长度的随机字符
 * @param   int       $l    指定长度
 * @param   string    $c    源字符集
 * @return  string
 */
function random($l,$c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'){
    $h = '';
    $m = strlen($c) - 1;
    for($i = 0; $i < $l; $i++){$h .= $c[mt_rand(0, $m)];}
    return $h;
}

/**
 * 生成密码
 * @param   string    $p   密码
 * @param   string    $s   密钥
 * @return  string
 */
function set_password($p,$s){
    return md5((is_md5($p) ? md5($p) : md5(md5($p))).$s);
}

/**
 * 设置订单号
 * @retrun  string 
 */
function set_order_id(){
    return date('YmdHis',time()).substr(microtime(),2,6).sprintf('%03d',rand(0,999));
}

/**
 * 字符串中间替换为星号
 * @param   string    $s    字符串
 * @param   string    $n    星号数 0:按字符算
 * @return  string
 */
function half_replace($s,$n=0){
    $l = mb_strlen($s, 'UTF-8');
    if($l<=2) return $s;
    $l = $n>0 ? $n : $l-2;
    return mb_substr($s, 0, 1, 'UTF-8') . str_repeat('*',$l) . mb_substr($s, -1, 1, 'UTF-8');
}

/**
 * 回车、换行、空格字符过滤
 * @param   string    $s   目标字符
 * @return  string
 */
function vtrim($s){
    return str_replace([chr(10),chr(13),"\t",' '],['','','',''],$s);
}

/**
 * 字符过滤 【空值或中间未出现空格均不过滤】
 * @param   string|array    $s    目标字符
 * @param   int             $t    过滤类型 默认1 1转码 0解码
 * @return  string|array
 */
function strip_sql($s,$t=1){
    if(is_array($s)){
        return array_map('strip_sql', $s);
    }else{
        if(empty($s)) return $s;
        $s = trim($s);
        if($t){
            global $_VFILTER;
            if($_VFILTER) $s = str_ireplace($_VFILTER,'',$s);
            if(strripos($s,' ') == 0) return $s;
            $p = 'vt_';
            $s = preg_replace("/\/\*([\s\S]*?)\*\//", "", $s);
            $s = preg_replace("/0x([a-f0-9]{2,})/i", '0&#120;\\1', $s);
            $s = preg_replace_callback("/(select|update|replace|delete|drop)([\s\S]*?)(".$p."|from)/i", 'strip_wd', $s);
            $s = preg_replace_callback("/(load_file|substring|substr|reverse|trim|space|left|right|mid|lpad|concat|concat_ws|make_set|ascii|bin|oct|hex|ord|char|conv)([^a-z]?)\(/i", 'strip_wd', $s);
            $s = preg_replace_callback("/(union|where|having|outfile|dumpfile|".$p.")/i", 'strip_wd', $s);
            return $s;
        }else{
            return str_replace(['&#95;','&#100;','&#101;','&#103;','&#105;','&#109;','&#110;','&#112;','&#114;','&#115;','&#116;','&#118;','&#120;'], ['_','d','e','g','i','m','n','p','r','s','t','v','x'], $s);
        }
    }
}

/**
 * 过滤扩展初始化，需要扩展过滤时前置于方法strip_sql调用该方法
 * @param   string   $filter    自定义过滤的字符串多个逗号,隔开，默认按系统配置 sys_filter 设置进行过滤
 * @global  array    $_VFILTER
 */
function strip_sql_extend($filter = ''){
    global $_VFILTER;
    $filter = $filter ?: vconfig('sys_filter');
    $_VFILTER = $_VFILTER ?: ($filter ? explode(',', $filter) : []);
}

/**
 * 转ASCII码 (以上方法 strip_sql 中用于转换ASCII码仿SQL注入)
 * @param   array   $m   对象
 * @return  string
 */
function strip_wd($m){
    if(is_array($m) && isset($m[1])){
        $wd = substr($m[1], 0, -1).'&#'.ord(strtolower(substr($m[1], -1))).';';
        if(isset($m[3])) return $wd.$m[2].$m[3];
        if(isset($m[2])) return $wd.$m[2].'(';
        return $wd;
    }
    return '';
}

/**
 * HTML过滤
 * @param   string|array   $str    目标
 * @param   int            $low    级别 默认1全过滤，0简单标签过滤
 * @return  string|array
 */
function strip_html($str,$low = 1){
    if(is_array($str)){
        return array_map('strip_html', $str, ['low'=>$low]);
    }elseif(!empty($str)){
        $str = htmlspecialchars_decode(trim($str));
        $str = strip_tags($str);
        if($low){
            $str = str_replace(['"',"\\","'","/","..","../","./","//"],'',$str);
            $no = '/<!--.*-->/';
            $str = preg_replace("$no",'',$str);
            $no = '/%0[0-8bcef]/';
            $str = preg_replace($no,'',$str);
            $no = '/%1[0-9a-f]/';
            $str = preg_replace($no,'',$str);
            $no = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';
            $str = preg_replace($no,'',$str);
        }
    }
    return $str;
}

/**
 * 转换HTML实体(双引号、单引号均转换)
 * @param   string   $s   目标字符
 * @return  string
 */
function vhtmlspecialchars($s){
    if(is_array($s)){
        return array_map('vhtmlspecialchars', $s);
    }else{
        $s = htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
        return str_replace('&amp;', '&', $s);
    }
}

/**
 * 数字格式转换
 * @param    float   $v   数值
 * @param    int     $p   小数点后位数
 * @param    bool    $s   是否格式化为字符串
 * @return   float/string
 */
function dround($v, $p=2, $s=false){
    $v = round(floatval($v), $p);
    if($s) $v = sprintf('%.'.$p.'f', $v);
    return $v;
}

/**
 * 获取扩展名
 * @param    string    $f    文件路径串
 * @return   string
 */
function file_ext($f){
    if(strpos($f, '.') === false) return '';
    $ext = strtolower(trim(substr(strrchr($f, '.'), 1)));
    return preg_match("/^[a-z0-9]{1,10}$/", $ext) ? $ext : '';
}
/**
 * 键串转换键值串
 * @param   string   $ids   键串
 * @param   array    $arr   数组
 * @return  string
 */
function idstoname($ids,$arr){
    $str = '';
    $a = explode(',', $ids);
    foreach($a as $i){
        $t = $arr[$i] ?? '';
        if($t) $str .= $str ? '，'.$t : $t;
    }
    return $str;
}
/**
 * 时间格式
 * @param  int  $time   时间戳
 * @return string
 */
function show_time($time){
    $rtime = date("Y-m-d H:i", $time);
    $time = time() - $time;
    if($time < 60){
        $str = '刚刚';
    }elseif($time < 3600){
        $str = floor($time / 60) . '分钟前';
    }elseif($time < 86400){
        $str = floor($time / 3600) . '小时前';
    }elseif($time < 259200){
        $str = floor($time / 86400) == 1 ? '昨天' : '前天';
    }else{
        $str = $rtime;
    }
    return $str;
}
if(!function_exists('password')){
    /**
     * 密码
     * @param $password
     * @return string
     */
    function password($password,$typ=PASSWORD_DEFAULT)
    {
        return password_hash($password, $typ);
    }

}